package com.iso8583.util;

public class StringToAscii {
    private static String toHexUtil(int n){
        System.out.println("toHexUtil-->n: "+n);
        String rt="";
        switch(n){
            case 10:rt+="A";break;
            case 11:rt+="B";break;
            case 12:rt+="C";break;
            case 13:rt+="D";break;
            case 14:rt+="E";break;
            case 15:rt+="F";break;
            default:
                rt+=n;
                System.out.println("toHexUtil-->rt:"+rt);
        }
        return rt;
    }

    public static String toHex(int n){
        StringBuilder sb=new StringBuilder();
        if(n/16==0){
            return toHexUtil(n);
        }else{
            String t=toHex(n/16);
            int nn=n%16;
            sb.append(t).append(toHexUtil(nn));
            System.out.println("toHexUtil(nn): "+toHexUtil(nn));
        }
        System.out.println("toHex: "+sb.toString());
        return sb.toString();
    }

    public static String parseAscii(String str){
        StringBuilder sb=new StringBuilder();
        byte[] bs=str.getBytes();
        for(int i=0;i<bs.length;i++){
            System.out.println("parseAscii: "+bs[i]);
            sb.append(toHex(bs[i]));
        }
        return sb.toString();
    }

    public static String hexToChar(String ASCII){
        StringBuffer sbf = new StringBuffer(ASCII);
        StringBuffer val = new StringBuffer();
        for(int i=0;i<ASCII.length();i++){
            if(i%2 == 1){
                String str = sbf.substring(i-1,i+1);
                int a = Integer.valueOf(str.substring(0, 1)).intValue();
                int b = Integer.valueOf(str.substring(1, 2)).intValue();
                char ch = (char) (a*16+b);
                val.append(ch);
            }
        }

        return val.toString();
    }

    public static void main(String args[]){
        String s="313536";
        System.out.println("转换后的字符串是："+StringToAscii.hexToChar(s));
    }
}
